/**
 *
 * AtJava source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to obinary.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 Atjava.com Ltd. (http://www.atjava.com) All rights reserved.
 *
 */
package com.atjava.jcrt.core.version;

import java.util.ArrayList;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;

import com.atjava.jcrt.BaseInfo;
import com.atjava.jcrt.core.ContentData;

/**
 * 
 * @author biggie
 * @version $Revision: 1.3 $ $Date: 2008/07/11 07:17:14 $
 */
public class VersionImpl implements com.atjava.jcrt.core.version.Version {

	private Node node = null;

	private List<Object> allVersion = null;

	private BaseInfo baseInfo = null;

	public VersionImpl(Node node, BaseInfo baseInfo) throws VersionException{
		this.node = node;
		this.baseInfo = baseInfo;
		this.init();
	}

	private void init() throws VersionException {
		try {
			allVersion = new ArrayList<Object>();
			VersionHistory vh = this.node.getVersionHistory();
			VersionIterator vi = vh.getAllVersions();
			vi.skip(1);
			while (vi.hasNext()) {
				Version v = vi.nextVersion();
				NodeIterator ni = v.getNodes();
				BaseInfo info = (BaseInfo) baseInfo.clone();
				while (ni.hasNext()) {
					Node nv = ni.nextNode();
					ContentData cdata = new ContentData(nv);
					info = (BaseInfo) cdata.changeToInfoClass(info);
					info.setNode(nv);
				}
				allVersion.add(info);
			}
		} catch (CloneNotSupportedException e) {
			throw new VersionException("CloneNotSupportedException", e);
		} catch (UnsupportedRepositoryOperationException e) {
			throw new VersionException("UnsupportedRepositoryOperationException", e);
		} catch (RepositoryException e) {
			throw new VersionException("RepositoryException", e);
		}
	}

	public List<Object> getAllVersion() {
		return this.allVersion;
	}

	public Object getFirstVersion() {
		if (this.allVersion != null && this.allVersion.size() > 0) {
			return this.allVersion.get(0);
		}
		return null;
	}

	public Object getLastVersion() {
		if (this.allVersion != null && this.allVersion.size() > 0) {
			return this.allVersion.get(this.allVersion.size() - 1);
		}
		return null;
	}

	public int getVersionNumber() {
		if (this.allVersion != null && this.allVersion.size() > 0) {
			return this.allVersion.size();
		}
		return 0;
	}

}
